package util
import (
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	_ "github.com/denisenkom/go-mssqldb"
	"gopkg.in/gorp.v1"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mssql"
	"fmt"
	"github.com/maxwellhealth/bongo"
	//"log"
	"gopkg.in/mgo.v2"
)

/*
dbType mssql mysql
 */
func InitGorp (connstr,dbType string) *gorp.DbMap {
//	var connstr="tcp:192.168.9.100:3306*dataExport/root/1mdata"
//	var connstr="root:emdata2015@tcp(192.168.9.100:3306)/dataExport"
//	msStr = flag.String("conn", "server=test;database=opc;port=4331;user id=sa;password=intime@123", "ms数据库连接串")
	db, err := sql.Open(dbType,  connstr)
	if err!=nil{
		fmt.Println(err);
		panic(err)
	}
	err=db.Ping()
	if err!=nil{
		fmt.Println(err);
		panic(err)
	}
	// construct a gorp DbMap
	var dbmap *gorp.DbMap
	if dbType=="mysql"{
		dbmap = &gorp.DbMap{Db: db, Dialect: gorp.MySQLDialect{"InnoDB", "UTF8"}}
	}else{
		dbmap = &gorp.DbMap{Db: db, Dialect: gorp.SqlServerDialect{}}
	}
	fmt.Println("initdb~", dbType,connstr);
	return dbmap
}


/*
dbType mssql mysql
 */
func InitGormBD (connstr string, dbType string) *gorm.DB {
	//	var connstr="tcp:192.168.9.100:3306*dataExport/root/1mdata"
	//	var connstr="root:emdata2015@tcp(192.168.9.100:3306)/dataExport"
	db, err := gorm.Open(dbType,  connstr)
	if err!=nil{
		fmt.Println(err);
		panic(err)
	}
	fmt.Println("InitGormBD,dbType",dbType,connstr);
	gorm.DefaultCallback.Create().After("gorm:begin_transaction").Remove("mssql:set_identity_insert")
	return db
}


func  InitODB (connstr string) *sql.DB {
	db, err := sql.Open("mysql",  connstr)
	if err!=nil{
		fmt.Println(err);
		panic(err)
	}
	return db
}

var dbname="bongoz"
func GetBongoConnection() *bongo.Connection {
	conf := &bongo.Config{
		ConnectionString: "localhost",
		Database:         dbname,
	}
	conn, err := bongo.Connect(conf)

	if err != nil {
		panic(err)
	}
	return conn
}
func GetMgoConnection() *mgo.Database {

	URL := "localhost"
	session, err := mgo.Dial(URL)  //连接数据库
	if err != nil {
		panic(err)
	}
	return session.DB(dbname)
}



